var flowchart_color_default = 'gray';
var overlay_width = 12;
var overlay_height = 12;
var overlay_location_reverse = 0;
var overlay_location = 1;
var overlay_location_self = 0.5;

var flowchart = {

    currentNode: {},
    currentLine: {},
    commonStyle: {
        isSource: true,
        isTarget: true,
        beforeDrop: function (connInfo) {
            var me = this;
            return checkConnection(me, connInfo);
        },
        viewStyle: {
            hoverPaintStyle: {
                outlineStroke: 'red',
                strokeWidth: 0
            }
        }
    },

// 初始化，返回流程图的对象
    init: function (_id) {
        var me = this;
        var initProperty = {
            Connector: ["Flowchart", {
                stub: [0, 18],
                gap: 3,
                cornerRadius: 5,
                alwaysRespectStubs: false
            }],
            Endpoint: ["Dot", {}],
            ConnectionsDetachable: false,
            MaxConnections: -1,
            ConnectionOverlays: [
                ["Arrow", {
                    location: overlay_location,
                    width: overlay_width,
                    length: overlay_height,
                    paintStyle: {
                        fill: flowchart_color_default
                    }
                }]
            ],
            EndpointStyle: {
                radius: 3,
                fill: flowchart_color_default
            },
            PaintStyle: {
                outlineStroke: flowchart_color_default,
                strokeWidth: 0
            },
            HoverPaintStyle: {
                outlineStroke: flowchart_color_default,
                strokeWidth: 3
            }
        }
        var instance = jsPlumb.getInstance(initProperty);

        instance.bind("click", function (conn, originalEvent) {
            flowchart.currentLine = conn;

            var sourceId = conn.sourceId;
            var targetId = conn.targetId;

            //正向连线
            var connectionsReverse = me.instance.getConnections({
                source: targetId,
                target: sourceId
            });

            if (connectionsReverse.length > 0) {
                var connAnchor_s = conn.endpoints[0].anchor
                var connAnchor_t = conn.endpoints[1].anchor
                var connReverseAnchor_s = connectionsReverse[0].endpoints[0].anchor
                var connReverseAnchor_t = connectionsReverse[0].endpoints[1].anchor

                var sourcePointEqualTargetPoint = connReverseAnchor_t.x == connAnchor_s.x && connReverseAnchor_t.y == connAnchor_s.y
                var targetPointEqualSourcePoint = connReverseAnchor_s.x == connAnchor_t.x && connReverseAnchor_s.y == connAnchor_t.y

                if (sourcePointEqualTargetPoint && targetPointEqualSourcePoint) {

                    var connTarget = $('#' + targetId).text()
                    var connReverseTarget = $('#' + sourceId).text()

                    layer.confirm('请选择目标节点：', {
                            icon: 3,
                            title: '提示',
                            btn: [connTarget, connReverseTarget, "取消"]
                        },
                        function (index) {
                            getNextActivityAndShow();
                            closeLayer(index)
                        }, function (index) {
                            flowchart.currentLine = connectionsReverse[0];
                            getNextActivityAndShow();
                            closeLayer(index)
                        }
                    );
                } else {
                    getNextActivityAndShow();
                }
            } else {
                getNextActivityAndShow();
            }

        });
        //连接事件
        instance.bind("connection", function (connInfo) {
            // console.log(connInfo)

            var sourcePoint = getconnetionPoint(connInfo.connection.endpoints[0].anchor)
            var targetPoint = getconnetionPoint(connInfo.connection.endpoints[1].anchor)

            var sourceId = connInfo.sourceId;
            var targetId = connInfo.targetId;

            //createConnectionFlag：标识是否要在后台创建数据，避免初始化连线的时候重复向后台提交数据。
            if (createConnectionFlag) {
                createConnection(sourceId, sourcePoint, targetId, targetPoint, wfId);
            }

            instance.addEndpoint(sourceId, {anchor: sourcePoint}, me.commonStyle)
            instance.addEndpoint(targetId, {anchor: targetPoint}, me.commonStyle)
        });

        me.instance = instance;

    },

    /**
     * 添加连接点
     * @param activity jsPlumb.getSelector获取的对象
     * @param _anchors 需要添加的点
     */

    addEndpoint: function (nodeId, _anchors) {
        var me = this;
        var instance = me.instance;

        if (!_anchors) {
            _anchors = ["BottomCenter", "TopCenter", "LeftMiddle", "RightMiddle"];
        }
        for (var i = 0; i < _anchors.length; i++) {
            var uuid = nodeId + "_" + _anchors[i];

            instance.addEndpoint(nodeId, {
                uuid: uuid,
                anchor: _anchors[i]
            }, me.commonStyle);
        }
    },

};

/*
    * 把端点坐标转换为描述
    * */
function getconnetionPoint(point) {
    var pointx = point.x
    var pointy = point.y
    var strxy = "x" + pointx + "y" + pointy

    switch (strxy) {
        case "x0y0.5":
            return "LeftMiddle"
        case "x1y0.5":
            return "RightMiddle"
        case "x0.5y0":
            return "TopCenter"
        case "x0.5y1":
            return "BottomCenter"
        default:
            return "err"
    }
}

